//
//  SalaryFlowDetailConttroller.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/24.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import MJRefresh
import Moya
import ObjectMapper
class SalaryFlowDetailConttroller: UIViewController {
    var companyID:String?
    var companyName:String?
    lazy var itemArray : [SalaryRecordModel] = [SalaryRecordModel]()
    fileprivate var totalPage:Int?
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.tableFooterView = UIView()
            _tableView.showsVerticalScrollIndicator = false
            _tableView.backgroundColor = UIColor.mg_backgroundGray
            
            _tableView.register(UITableViewCell.self, forCellReuseIdentifier: "\(UITableViewCell.self)")
            _tableView.register(SalaryFlowDetailCell.self, forCellReuseIdentifier: "\(SalaryFlowDetailCell.self)")
            
            return _tableView
        }
    }
//    fileprivate lazy var topView:SalaryDetailTopView = {
//        let topView = SalaryDetailTopView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 45))
//        return topView
//    }()
    
    fileprivate lazy var bottomImageView:UIImageView = {
        let bottomImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 80, height: 78))
        bottomImageView.image = UIImage(named: "rethen_kong")
        return bottomImageView
    }()
    
    
    fileprivate var currentPage = 1

    override func viewDidLoad() {
        super.viewDidLoad()
//        self.view.addSubview(topView)
//        self.topView.snp.makeConstraints { (make) in
//            make.top.equalTo(self.view).offset(64)
//            make.left.right.equalTo(self.view).offset(0)
//            make.height.equalTo(45)
//        }
       // self.topView.companyName.text = self.companyName
        self.view.addSubview(bottomImageView)
        self.bottomImageView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(150)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 80, height: 78))
        }
        
        self.title = "发放明细"
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
//        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "点击", style: .done, target: self, action: #selector(doRightAction))
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10)
        self.tableView.separatorInset = UIEdgeInsets.zero
        self.tableView.separatorStyle = .singleLine
        self.tableView.separatorColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.showsVerticalScrollIndicator = false
        self.tableView.showsHorizontalScrollIndicator = false
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(89)
            make.left.right.bottom.equalTo(self.view)
        }
        self.view.bringSubview(toFront: self.tableView)
        let tableFooter = MJRefreshAutoNormalFooter { [unowned self] in
            self.getNextPage()
        }
        self.tableView.mj_footer = tableFooter
        
        self.getData()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    func getData() {
        
        guard (self.companyID != nil) else {
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        self.currentPage = 1
    LCAPiSubManager.request(.GetSalaryPayedRecord(contructionCompanyID: companyID!, AccountId: accountId, pageIndex: 1, pageSize: 25)) { (result) in
        if case let .success(response) = result {
            guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                return
            }
            
            guard (jsonString["State"]) as! String == "OK" else{
                return
            }
            
            
            guard  let resultDic : NSDictionary = jsonString["Result"] as? NSDictionary else{
                return
            }
            guard  let resultArray : NSArray = resultDic["ProjectList"] as? NSArray else{
                return
            }
            if let totalList = resultDic["Total"] as? Int {
                self.totalPage = (totalList/25)+1
            }
            self.itemArray = Mapper<SalaryRecordModel>().mapArray(JSONObject: resultArray)!
            self.tableView.reloadData()
            
        }
    }
    }
    
    func getNextPage() {
        guard (self.totalPage != nil) else {
            return
        }
        if self.currentPage >= self.totalPage! {
       self.tableView.mj_footer.endRefreshingWithNoMoreData()
            return
        }
        
        guard (self.companyID != nil) else {
            return
        }
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        self.currentPage += 1
        
    LCAPiSubManager.request(.GetSalaryPayedRecord(contructionCompanyID: companyID!, AccountId: accountId, pageIndex: self.currentPage, pageSize: 25)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                
                
                guard  let resultDic : NSDictionary = jsonString["Result"] as? NSDictionary else{
                    return
                }
                guard  let resultArray : NSArray = resultDic["ProjectList"] as? NSArray else{
                    return
                }
                var salaryArray = [SalaryRecordModel].init()
                salaryArray = Mapper<SalaryRecordModel>().mapArray(JSONObject: resultArray)!
                if salaryArray.count <= 0 {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
                    return
                }
                self.itemArray += salaryArray
                self.tableView.reloadData()
                self.tableView.mj_footer.endRefreshing()
            }
        }
    }

}

extension SalaryFlowDetailConttroller: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.itemArray.count == 0 {
            self.tableView.isHidden = true
        }else{
            self.tableView.isHidden = false
        }
        
        return self.itemArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(SalaryFlowDetailCell.self)", for: indexPath) as! SalaryFlowDetailCell
        cell.bind(self.itemArray[indexPath.row])
        return cell
    }
}
